package com.example.lin.day9_28;

import android.app.Activity;
import android.content.Context;
import android.view.View;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class ButterKnife {

    public static void init(final Activity activity) {

        Class<? extends Context> c = activity.getClass();

        Field[] declaredFields = c.getDeclaredFields();
        for (Field f :
                declaredFields) {
            BindView annotation = f.getAnnotation(BindView.class);
            if (annotation != null) {
                int value = annotation.value();
                View viewById = activity.findViewById(value);
                try {
                    f.set(activity, viewById);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }


        Method[] declaredMethods = c.getDeclaredMethods();
        for (final Method m : declaredMethods) {
            OnClick annotation = m.getAnnotation(OnClick.class);
            if (annotation != null) {
                int value = annotation.value();
                View viewById = activity.findViewById(value);
                viewById.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            m.invoke(activity, v);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }

        }


    }
}
